import React, { Component } from 'react';
import { View, Text, Date, StyleSheet, SectionList } from 'react-native';

import request from '../../utils/request';

import DetailItem from './DetailItem'
import AttachmentUpload from './AttachmentUpload'

// import navigationUtil from '../../utils/navigation';
import moment from 'moment';

import { storage } from '../../utils/storage';

import ActionSheet from 'react-native-actionsheet'

import DateTimePicker from 'react-native-modal-datetime-picker';

//图片选择器
var ImagePicker = require('react-native-image-picker');

//图片选择器参数设置
var options = {
    title: '',
    cancelButtonTitle: '取消',
    takePhotoButtonTitle: '拍照',
    chooseFromLibraryButtonTitle: '相册',
    // customButtons: [
    //     { name: 'hangge', title: 'hangge.com图片' },
    // ],
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
};


class ExpendDetail extends Component {


    static navigationOptions = ({ navigation, screenProps }) => ({
        // title: navigation.state.params?navigation.state.params.title:null,
        headerTitle: navigation.state.params.title,
        headerStyle: { backgroundColor: 'rgba(0,171,236,1)' },//导航栏的样式

    });

    constructor(props) {
        super(props)
        this.state = {
            cityName: '必填',
            cityColor: 'gray',
            hotelName: ' ',
            hotelColor: 'gray',
            beginTime: '必填',
            beginTiemColor: 'gray',
            endTime: '必填',
            endTimeColor: 'gray',
            isConpany: '是',
            days: '必填',
            daysColor: 'gray',

            invoiceText: '添加增值税发票',
            invoiceColor: 'gray',

            moneyText: '0.00',

            markText: '未设置',
            markTextColor: 'gray',

            AttachmentImgs: [{ imgName: '上传', id: '0' }],
            progressText: '0/6',
            selectImgNum: 0,


            //
            id: 0,
            //是否显示时间选择
            isDateTimePickerVisible: false,
            DateselectID: 0,

            //sheet
            actionsheetTitle: '请选择地点',
            actionsheetArray: ['上海', '北京', '深圳', '取消'],

        }
    }


    render() {
        var dataSource = [
            {
                key: '1',
                data: [{ icon: '终点', name: '出差城市', placeHolder: this.state.cityName, color: this.state.cityColor, id: 10 },
                { icon: '酒店名称', name: '酒店名称', placeHolder: this.state.hotelName, color: this.state.hotelColor, id: 11 },
                { icon: '开始时间1', name: '入住时间', placeHolder: this.state.beginTime, color: this.state.beginTiemColor, id: 12 },
                { icon: '结束时间1', name: '退房时间', placeHolder: this.state.endTime, color: this.state.endTimeColor, id: 13 },
                { icon: '劳务提供人1', name: '是否为公司员工', placeHolder: this.state.isConpany, color: 'black', id: 14 },
                { icon: '天数月数日期1', name: '住宿天数', placeHolder: this.state.days, color: this.state.daysColor, id: 15 },]
            },
            {
                key: '2',
                data: [{ icon: '税务', name: '增值税发票', placeHolder: this.state.invoiceText, color: this.state.invoiceColor, id: 21 },
                { icon: '金额1', name: '总金额', placeHolder: 'CNY', color: 'black', text: this.state.moneyText, id: 22 },]
            },
            {
                key: '3',
                data: [{ attachment: '上传附件', progressText: this.state.progressText, imgs: this.state.AttachmentImgs }],
            },
            {
                key: '4',
                data: [{ icon: '备注', name: '备注', placeHolder: this.state.markText, color: this.state.markTextColor, id: 41 },]
            },
        ]
        return (
            <View style={{ flex: 1 }}>
                <SectionList
                    keyExtractor={this._keyExtractor}
                    data={dataSource}
                    renderItem={this._renderItem}
                    renderSectionHeader={this._sectionComp}
                    sections={dataSource}
                />
                {this.initActionSheet()}
                {this.renderDateTimePicker()}
            </View>
        );

    }

    componentDidMount() {

        storage.load({
            key: 'accessUserData'
        }).then(result => {

            request({
                method: 'POST',
                url: 'basebills/queryBasebills',
                data: { bookId: this.props.navigation.state.params.itemData.item.id },
                access_token: result.token,
            })
                .then((data) => {

                    let detailData = data.data;
                    this.setState({
                        cityName: detailData.htBusinessAddress.city,
                        cityColor: 'black',
                        hotelName: ' ',
                        hotelColor: 'gray',
                        beginTime: moment(detailData.htCheckInTime).format("YYYY-MM-DD"),
                        beginTiemColor: 'black',
                        endTime: moment(detailData.htCheckOutTime).format("YYYY-MM-DD"),
                        endTimeColor: 'black',
                        isConpany: '是',
                        days: detailData.htDays,
                        daysColor: 'black',
                    })
                })
        })
    }


    //初始化时间选择
    renderDateTimePicker() {
        return (
            <DateTimePicker
                titleIOS={'选择时间'}
                cancelTextIOS={'取消'}
                confirmTextIOS={'确定'}
                mode={'datetime'}
                isVisible={this.state.isDateTimePickerVisible}
                onConfirm={this.handleDatePicked.bind(this)}
                onCancel={this.hideDateTimePicker.bind(this)} />
        )
    }
    //隐藏
    hideDateTimePicker() {
        this.setState({ isDateTimePickerVisible: false })
    }

    handleDatePicked(date) {
        this.setState({ isDateTimePickerVisible: false })
        var DateFormat = moment(date).format("YYYY-MM-DD HH:mm");

        if (this.state.DateselectID == 12) {
            this.setState({
                beginTime: DateFormat,
                beginTiemColor: 'black'
            })
        } else {
            this.setState({
                endTime: DateFormat,
                endTimeColor: 'black'
            })
        }


    }


    //id
    _keyExtractor = (item, index) => index + item.id;

    //初始化ActionSheet
    initActionSheet() {
        return <ActionSheet
            ref={o => this.ActionSheet = o}
            title={this.state.actionsheetTitle}
            options={this.state.actionsheetArray}
            cancelButtonIndex={3}
            // destructiveButtonIndex={}
            onPress={(index) => {

                var str;
                if (this.state.DateselectID == 10 || this.state.DateselectID == 11) {

                    if (index == 0) {
                        str = "上海"
                    } else if (index == 1) {
                        str = '北京'
                    } else if (index == 2) {
                        str = '深圳'
                    }

                    if (str) {

                        this.setState({
                            cityName: str,
                            cityColor: 'black',
                            hotelName: str + '国际大酒店',
                            hotelColor: 'black'
                        })
                    }

                } else {

                    if (index == 0) {
                        str = "是"
                    } else if (index == 1) {
                        str = '否'
                    }
                    if (str) {
                        this.setState({
                            isConpany: str,
                        })
                    }

                }

            }}
        />
    }


    //ActionSheet SHOW
    showActionSheet = () => {
        this.ActionSheet.show()
    }

    //行点击
    itemClick = (itemData) => {

        this.setState({
            DateselectID: itemData.id,
        })

        switch (itemData.id) {
            case 10: {
                this.setState({
                    actionsheetTitle: '请选择地点',
                    actionsheetArray: ['上海', '北京', '深圳', '取消'],
                })
                this.showActionSheet();
            }
                break;
            case 11: {
                this.setState({
                    actionsheetTitle: '请选择地点',
                    actionsheetArray: ['上海', '北京', '深圳', '取消'],
                })
                this.showActionSheet();
            }
                break;
            case 12: {
                this.setState({ isDateTimePickerVisible: true })
            }
                break;
            case 13: {
                this.setState({ isDateTimePickerVisible: true })
            }
                break;
            case 14: {
                this.setState({
                    actionsheetTitle: '是否为公司员工',
                    actionsheetArray: ['是', '否', '取消']
                })
                this.showActionSheet();
            }
                break;
            case 15: {

                this.props.navigation.navigate('Input', {
                    title: '住宿天数', callback: (backData) => {
                        if (backData) {
                            this.setState({
                                days: backData,
                                daysColor: 'black'
                            })
                        }

                    }
                });
            }
                break;
            default:
                break;
        }

    }
    //金额输入
    onTextChangeText = (text) => {

        this.setState({
            moneyText: text,
        })
    }

    //区头
    _sectionComp = (info) => {

        if (info.section.key === '1') {
            return null;
        }
        return <Text
            style={{ height: 30, textAlign: 'center', textAlignVertical: 'center', backgroundColor: '#e8e8e8', color: 'white', fontSize: 30 }}>{}</Text>
    }
    //图片点击
    imgClick = (t) => {

        if (t.id === '0') {
            { this.takePhotoAndPic() }
        } else {
            alert('点击图片可以预览')
        }

    }
    //图片选择器
    takePhotoAndPic() {

        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('用户取消了选择！');
            }
            else if (response.error) {
                alert("ImagePicker发生错误：" + response.error);
            } else {
                let source = { uri: response.uri };

                var num = this.state.selectImgNum + 1;
                var iddd = this.state.id + 1;
                this.state.AttachmentImgs.unshift(
                    { imgName: response.uri, id: iddd }
                )

                this.setState({
                    selectImgNum: num,
                    progressText: num + '/' + '6',
                    id: iddd
                });
            }
        });

    }



    //图片长按
    imgLongPregress = (t) => {

        if (t.id === '0') {

        } else {

            var num = this.state.selectImgNum - 1;


            for (var i = 0; i < this.state.AttachmentImgs.length; i++) {

                var obj = this.state.AttachmentImgs[i]
                if (t.id === obj.id) {
                    this.state.AttachmentImgs.splice(i, 1)
                    break;
                }
            }

            this.setState({
                selectImgNum: num,
                progressText: num + '/' + '6',
            });
        }
    }


    //cellforrow
    _renderItem = (rowData) => {

        if (rowData.section.key === '3') {

            return (
                <AttachmentUpload
                    status={this.props.navigation.state.params.status}
                    rowData={rowData.item}
                    imgClick={(t) => this.imgClick(t)}
                    imgLongPregress={(t) => this.imgLongPregress(t)}
                />
            )
        }
        return (
            <DetailItem
                status={this.props.navigation.state.params.status}
                key={rowData.name}
                rowData={rowData.item}
                itemClick={(rowData) => this.itemClick(rowData)}
                onTextChangeText={(text) => this.onTextChangeText(text)}
            />
        )
    }

}

export default ExpendDetail;

const styles = StyleSheet.create({

    datePickerContainer: {
        flex: 1,
        borderRadius: 5,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'white',
        marginBottom: 10,
    },
})